import { prevPdf } from '@/api/http'

    //去除时间末尾00
export function removeZero(dateString) {
    // 使用slice方法截取除了最后两位的字符串
    return dateString.slice(0, -3);

}


export function extractPaths(menusPath, resultArr) {
    menusPath.forEach(obj => {
        const currentPath = obj.path ? obj.path : ''
        resultArr.push(currentPath);
        if (obj.children && obj.children.length > 0) {
            extractPaths(obj.children, resultArr);
        }
    });
    // console.log(resultArr,'11111');
}
export function filterMenus(outpath, spath) {
    const menusArr = uni.getStorageSync('menusPath')
    const idx = menusArr.findIndex(v => v.path === outpath)
    if (idx === -1) {
        // 没有这个权限
        return false
    } else if (idx > -1) {
        const paths = []
        extractPaths([menusArr[idx]], paths)
        const re = paths.includes(spath)
        return re
    }
}

export function getFileSize(size) {
    // const size = size;
    const units = ["B", "KB", "MB", "GB", "TB"];
    let i = 0;
    while (size >= 1024 && i < units.length - 1) {
      size /= 1024;
      i++;
    }
    return size.toFixed(2) + " " + units[i];
  }





// 时间戳转换为 年月日 时分秒
export function formatTimestamp(timestamp, type) {
    let date;
    date = timestamp ? new Date(timestamp) : new Date();
    // 获取年月日
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    // 获取小时分钟
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    // 拼接为最终格式的字符串
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
    if (type === 'YYYY-MM-DD') {
        return `${year}-${month}-${day}`
    }

    return formattedDate;
}

// 示例用例
const timestamp = 1695415800000; // 假设传入的时间戳是 1695415800000 (对应2023年10月22日10点30分)
const formattedDateTime = formatTimestamp(timestamp);


export function getDateRange(interval) {
    const currentDate = new Date();
    let startDate = new Date();

    if (interval === 'oneMonth') {
        startDate.setMonth(startDate.getMonth() - 1);
    } else if (interval === 'threeMonths') {
        startDate.setMonth(startDate.getMonth() - 3);
    } else if (interval === 'sixMonths') {
        startDate.setMonth(startDate.getMonth() - 6);
    } else if (interval === 'oneYear') {
        startDate.setFullYear(startDate.getFullYear() - 1);
    }

    const range = [startDate.toISOString().slice(0, 10), currentDate.toISOString().slice(0, 10)];
    return range;
}

//预览
export async function viewFile(row) {
    const fileArr = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
    const imgArr = ['png', 'jpeg', 'jpg', 'webp']
    const mediaArr = ['mp4']
    const compressArr = ['zip', 'rar', '7z']
    let arr = row.fileSuffix.split('.')
    let fileType = arr[arr.length - 1]
    if (fileArr.indexOf(fileType) !== -1) {
        handleTypeInfo('4', row)
    } else if (fileType === 'pdf') {
        handleTypeInfo('2', row)
    } else if (imgArr.indexOf(fileType) !== -1) {
        handleTypeInfo('1', row)
    } else if (mediaArr.indexOf(fileType) !== -1) {
        handleTypeInfo('3', row)
    } else if (compressArr.indexOf(fileType) !== -1) {
        // 压缩包  直接下载
        downloadByFileid(row)
    }
}

function downloadByFileid(row) {
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = row.url;
    tempLink.setAttribute("download", row.originalName);
    tempLink.setAttribute("target", "_blank");
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
};

function handleTypeInfo(type, row) {
    let item = {
        type: type,
        name: row.originalName,
        src: row.url,
        fileName: row.fileName
    }
    uni.navigateTo({
        url: '/pages/preview/index?item=' + encodeURIComponent(JSON.stringify(item))
    })
}






// let item = {
//     type: '2',
//     name: '属于',
//     src: 'http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf'
// }

// uni.navigateTo({
//     url: '/pages/preview/index?item=' + encodeURIComponent(JSON.stringify(item))
// })














/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content) {
    uni.showToast({
        icon: 'none',
        title: content
    })
}

/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
    return new Promise((resolve, reject) => {
        uni.showModal({
            title: '提示',
            content: content,
            cancelText: '取消',
            confirmText: '确定',
            success: function(res) {
                resolve(res)
            }
        })
    })
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName]
        var part = encodeURIComponent(propName) + "="
        if (value !== null && value !== "" && typeof(value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']'
                        var subPart = encodeURIComponent(params) + "="
                        result += subPart + encodeURIComponent(value[key]) + "&"
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&"
            }
        }
    }
    return result
}